package com.spring.hot;



/**
 * 链表问题,构建新链表
 * @author Cizai
 * @since 2022/11/29 10:10
 **/
public class 两树相加 {

    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {

        if (l1==null) return l2;
        if (l2==null) return l1;

        ListNode p1 = new ListNode(-1);
        ListNode p2 = p1;
        // 设定进位
        int k =0;
        // 如果l1，l2不为null或者进位还存在则一直去构建新的链表
        while (l1 != null || l2 != null || k>0 ) {

            // 保存当前两个值相加的值
            int temp = 0;
            if (l1!=null){
                temp = temp+l1.val;
                l1 = l1.next;
            }

            if (l2 != null){
                temp = temp + l2.val;
                l2 = l2.next;
            }

            temp = temp + k;

            p2.next = new ListNode(temp%10);

            p2 = p2.next;
            k = temp/10;

        }

        return p1.next;

    }
}

 class ListNode {
    int val;
    ListNode next;
    ListNode() {}
    ListNode(int val) { this.val = val; }
    ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}